package com.onclick.webchat.controller;

import java.time.LocalDateTime;
import java.util.Vector;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;

@ServerEndpoint(value = "/messageService")
public class ChatServerController {
	 private static Vector<Session> room = new Vector<Session>();
	 @OnOpen
	    public void onOpen(Session session){
	        room.addElement(session);
	    }
	@OnMessage
	public void pushMessage(String message,Session session) {
		
		JSONObject json = JSONObject.parseObject(message);
		LocalDateTime date = LocalDateTime.now();
		
	    json.put("data", date);
	    for(Session se : room){
            //设置消息是否为自己的
	    	   json.put("isSelf", se.equals(session));
            //发送消息给远程用户
            se.getAsyncRemote().sendText(json.toString());
        }
	}
	  /* 用户断开
	     * @param session
	     */
	    @OnClose
	    public void onClose(Session session){
	        room.remove(session);
	    }
	    /**
	     * 用户连接异常
	     * @param t
	     */
	    @OnError
	    public void onError(Throwable t){
	    }
}
